import { computed, unref, ref, ComputedRef, watch } from 'vue';
import { VxeGridPropTypes } from 'vxe-table';

import type { TableProps } from '../types/table';
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '../const';

export function usePagination(refProps: ComputedRef<TableProps>) {
  const configRef = ref<VxeGridPropTypes.PagerConfig>({});

  watch(
    () => unref(refProps).pagerConfig,
    (pagination) => {
      if (pagination) {
        configRef.value = {
          ...unref(configRef),
          ...(pagination || {}),
        };
      }
    },
  );

  const getPaginationInfo = computed((): VxeGridPropTypes.PagerConfig => {
    const { pagerConfig } = unref(refProps);
    return {
      size: 'small',
      layouts: [
        'Total',
        'PrevJump',
        'PrevPage',
        'Jump',
        'PageCount',
        'NextPage',
        'NextJump',
        'Sizes',
      ],
      // layouts: ['PrevJump', 'PrevPage', 'Number', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'Jump', 'FullJump', 'PageCount', 'Total'],
      currentPage: 1,
      pageSize: PAGE_SIZE,
      pageSizes: PAGE_SIZE_OPTIONS,
      autoHidden: false,
      ...(pagerConfig || {}),
      ...(unref(configRef) || {}),
    };
  });

  function setPagination(info: Partial<VxeGridPropTypes.PagerConfig>) {
    const paginationInfo = unref(getPaginationInfo);
    configRef.value = {
      ...(paginationInfo || {}),
      ...(info || {}),
    };
  }

  function getPagination() {
    return unref(getPaginationInfo);
  }

  return { getPaginationInfo, getPagination, setPagination };
}
